<template>
  <div class="task-detail-container customer-detail-view-v2" v-loading="loading" ref="container">
    <div v-if="!loading && !hasViewCustomerAuth">
      <no-auth></no-auth>
    </div>
    <!-- start 顶部操作区 -->
    <div class="task-detail-header common-detail-header" v-if="!loading && hasViewCustomerAuth" ref="header">
      <div class="task-detail-header-top" :class="{'active': !collapse}">
        <button
          type="button"
          class="btn btn-text"
          @click="goBack"
          v-if="allowBack">
          <i class="iconfont icon-arrow-left"></i>
        </button>
        <!-- start 折叠按钮 -->
        <div class="collapse-btn" @click="collapseBtn" v-if="false">
          <el-tooltip :content="collapse?$t('common.base.collapse'):$t('common.base.expand')" placement="top">
            <i class="iconfont icon-more"></i>
          </el-tooltip>
        </div>
        <!-- end 折叠按钮 -->

        <div class="flex-1 header-left-buttons">
          <el-button
            type="plain-third"
            @click="jump"
            v-if="allowEditCustomer"
            v-track="getBtnsTrackData('TO_EDIT')">
            <i class="iconfont icon-edit-square" ></i>{{$t('common.base.edit')}}
          </el-button>
          <el-button
            type="plain-third"
            @click="deleteCustomer"
            v-track="getBtnsTrackData('DELETE')"
            v-if="allowDeleteCustomer">
            <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
          </el-button>
          <el-dropdown @command="execAttentionCommand">
            <el-button
              type="plain-third">
              <i
                class="iconfont"
                :class="{
                  'icon-tianjiaguanzhu': !isAttention,
                  'icon-quxiaoguanzhu': isAttention
                }"></i>
              {{ isAttention? $t('customer.unsubscribe') : $t('customer.attention') }}
            </el-button>

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="toggle">{{ isAttention ? $t('customer.unsubscribe') : $t('customer.followCustomer') }}</el-dropdown-item>
              <el-dropdown-item command="view" :disabled="!hasEditCustomerAuth" v-track="getBtnsTrackData('CHECK_FOLLOWED')">{{$t('customer.viewFollowed')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            type="plain-third"
            @click="openDialog('remind')"
            v-if="!isDisable && isShowCustomerRemind"
            v-track="getBtnsTrackData('ADD_REMIND')">
            <i class="iconfont icon-bell" ></i>{{$t('common.base.addRemind')}}
          </el-button>


          
        </div>

        <div class="task-detail-btn-group header-right-buttons" style="margin-left:auto;">
          <el-dropdown
            @command='handleCommand'
            trigger="click"
            v-if="allowEditCustomer || (allowCreateProduct && !isBasicEditionHideProduct)">
            <el-button type="primary" size='small'>
              <i class="iconfont icon-add2"></i>{{$t('common.base.create')}}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command='contact' v-if="allowCreateLinkman" v-track="getBtnsTrackData('CREATE_LINKMAN')">{{$t('common.base.contact')}}</el-dropdown-item>
              <el-dropdown-item command='address' v-if="allowEditCustomer" v-track="getBtnsTrackData('CREATE_ADDRESS')">{{$t('common.base.address')}}</el-dropdown-item>
              <el-dropdown-item command='product' v-if="allowCreateProduct && !isBasicEditionHideProduct" v-track="getBtnsTrackData('CREATE_PRODUCT')">{{$t('common.base.product')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-dropdown trigger="click" v-if="allowCreateTask && isShowTaskModule">
            <el-button type="primary" size='small'>
              <i class="iconfont icon-add2"></i>{{$t('common.base.task')}}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <div class="task-type-dropdown-group">
                <el-dropdown-item v-for="(type, index) in taskTypes" :key="type.id">
                  <a
                    class="link-of-dropdown"
                    href="javascript:;"
                    @click.prevent="createTask(type.id)"
                    v-track="getBtnsTrackData('CREATE_TASK')">{{type.name}}</a>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>

          <el-dropdown trigger="click" v-if="allowCreateEvent && !isBasicEditionHideEvent">
            <el-button type="primary" size='small'>
              <i class="iconfont icon-add2"></i>{{$t('common.base.event')}}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <div class="task-type-dropdown-group">
                <el-dropdown-item v-for="event in eventTypes" :key="event.id">
                  <a
                    class="link-of-dropdown"
                    href="javascript:;"
                    @click.prevent="createEvent(event.id)"
                    v-track="getBtnsTrackData('CREATE_EVENT')">{{event.name}}</a>
                </el-dropdown-item>
              </div>
              
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="click" v-if="!isDelete && allowCreatePlanTask && isShowPlanTask && !isBasicEditionHidePlanWork">
            <el-button type="primary" size='small'>
              <i class="iconfont icon-add2"></i>{{$t('common.base.scheduledTasks')}}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="task in planTypeList" :key="task.id">
                <a
                  class="link-of-dropdown"
                  href="javascript:;"
                  @click.prevent="createPlanTask(task.id)"
                  v-track="getBtnsTrackData('CREATE_PLAN_TASK')">{{task.name}}</a>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- 更多操作 -->
          <el-dropdown v-if="isShowMoreOperation" @command="handleMoreOperationCommand" trigger="click">
            <el-button type="primary">
              {{ $t('common.base.more') }} <i class="iconfont icon-fdn-select"></i>
            </el-button>
            <el-dropdown-menu class="detail-more-dropdown-menu" slot="dropdown">
              <el-dropdown-item v-if="isShowCreateSmartPlan" command="smartPlan" >{{ $t('smartPlan.title') }}</el-dropdown-item>
              <el-dropdown-item v-if="allowEditCustomer" command="mergeCustomer">{{$t('customer.mergeCustomer.mergeCustomerBtn')}}</el-dropdown-item>
              <template v-if="pageButtonSetGray">
                <template v-for="(item, index) in pageButtonList">
                  <el-dropdown-item ><div @click="handlePageButtonClick(item)">{{ item.name }}</div></el-dropdown-item>
                </template>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <div class="task-detail-header-bottom bg-w" :class="{'active': !collapse}">
        <ul>
          <li>
            <div>
              <span class="tag-name">{{$t('customer.customerNo')}}：</span>
              <span>{{customer.serialNumber}}</span>
            </div>
            <div>
              <span class="tag-name">{{$t('common.base.contact')}}：</span>
              <span>{{customer.lmName}} {{customer.lmPhone}}
                <i class="iconfont icon-dianhua2" @click="makephoneCall" v-if="customer.lmPhone"></i>
              </span>
            </div>
          </li>
          <li>
            <div class="address-item">
              <span class="tag-name">{{$t('common.base.address')}}：</span>
              <span class="address-text"  @click="openMap">
                <i class="iconfont icon-address" v-if="lmAddress"></i>
                {{lmAddress}}

              </span>
            </div>
          </li>
          <li>
            <div>
              <span class="tag-name">{{$t('common.base.serviceTeam')}}：</span>
              <span>{{tags}}</span>
            </div>
            <div>
              <span class="tag-name">{{$t('customer.customerManagerName')}}：</span>
              <span>{{customer.customerManagerName}}</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- end 顶部操作区 -->

    <!-- start 客户详情折叠面板 -->
    <div class="task-detail-main" v-if="hasViewCustomerAuth" @scroll="getScroll">
      <BaseTileLayoutTabBar
        v-if="baseLayout === 1"
        :bar-list="taskLayoutTabBarList"
        :now-item="currTab"
        @changeItem="tabBarChangeItem"
        @openLayoutModal="openBaseLayoutModal"
      ></BaseTileLayoutTabBar>

      <base-collapse 
        class="task-detail-main-content detail-main-content" 
        :direction.sync="collapseDirection"
        :hidePartCollapse="hidePartCollapse">
        <template slot='left'>
          <div class="task-detail-main-content-left detail-main-content-left customer-content-left" v-show="collapseDirection != 'left'">
            <BaseTileLayoutTabBar
              v-if="baseLayout == 2"
              :bar-list="leftTabBarList"
              :now-item="currTab"
              @openLayoutModal="openBaseLayoutModal"
            ></BaseTileLayoutTabBar>
            <div class="customer-content-left-cell" :class="formCellCount > 1 ? 'bbx-normal-form-view-cell' : ''">
              <div class="customer-content-left-cell-con">
                <div class="detail-main-content-left-head">
                <div
                  class="head-label label-delete"
                  v-if="isDelete"
                  :title="$t('customer.detail.tip.customerDeleted')"
                  v-tooltip>{{$t('common.base.deleted')}}</div>
                <div
                  class="head-label label-disabled"
                  v-if="isDisable"
                  :title="$t('customer.detail.tip.customerDisabled')"
                  v-tooltip>{{$t('common.base.disabled')}}</div>
                <div class="main-name">
                  {{ customer.name }}
                  <ui-wx-tag is-text v-if="customer.hasWechat" />
                  </div>
                </div>
                <customer-tag-edit v-if="isShowCustomerTag" @change="onCustoemrTagChangeHandler" :customer-id="customer.id" :show-edit="allowEditCustomer" :value="customer.customerTag" />
                <customer-detail
                  :share-data="propsForSubComponents"
                  :init-data="initData"
                  :allow-edit-synergies="allowEditCustomer"
                  :form-cell-count="formCellCount"
                  @synergies-updated="synergiesUpdated"></customer-detail>
              </div>
            </div>
          </div>

          <div
            class="collapse-left"
            v-show="collapseDirection == 'left'">
            {{$t('customer.customerInfo')}}
          </div>
        </template>
        <!-- end 客户详情 -->

        <template slot="rightExtend">
          <button class="right-extend-btn" @click="currTabRight = 'customer-info-record'">
            <i class="iconfont icon-message1"></i>{{$t('common.base.addRemark')}}
          </button>
        </template>

        <template slot='right'>
          <div
            class="task-detail-main-content-right detail-main-content-right"
            ref="rightContent"
            v-if="!loading"
            v-show="collapseDirection != 'right'"
            v-loading="rightTabBarLoading">
            <BaseBarV3
              v-if="baseLayout == 2"
              :bar-list="tabBarList"
              :now-item="currTabRight"
              @changeItem="tabBarChangeItem"
              @upDateBarList="tabBarUpdateList">
              <template slot="tabitem-customer-info-record" slot-scope="{tabs}">
                <span class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.recordQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-contact-table" slot-scope="{tabs}">
                <span class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.linkmanQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-address-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.addressQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-contract" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.contractQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-product-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.productQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-call-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.callQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-task-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{taskLabel}}</span>
              </template>
              <template slot="tabitem-customer-event-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{eventLabel}}</span>
              </template>
              <template slot="tabitem-customer-plan-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.plantaskQuantity || 0})`}}</span>
              </template>
              <template slot="tabitem-customer-remind-table" slot-scope="{tabs}">
                <span  class="overHideCon-1">{{`${tabs[tabLabelKey]}(${StatisticalData.remindQuantity || 0})`}}</span>
              </template>
            </BaseBarV3>
            <customer-info-record v-if="currTabRight == 'customer-info-record'" :share-data="propsForSubComponents" :init-data="initData"></customer-info-record>
            <customer-contact-table
              v-else-if="currTabRight == 'customer-contact-table'"
              :share-data="propsForSubComponents"
              :extra-attrs="tableExtraAttrs"
              :init-data="initData"></customer-contact-table>
            <customer-address-table
              v-else-if="currTabRight == 'customer-address-table'"
              :share-data="propsForSubComponents"
              :extra-attrs="tableExtraAttrs"
              :init-data="initData"></customer-address-table>
            <customer-contract-table v-else-if="currTabRight == 'customer-contract'" :share-data="propsForSubComponents" type="customerContract"></customer-contract-table>
            <customer-product-table v-else-if="currTabRight == 'customer-product-table'" :share-data="propsForSubComponents" :extraAttrs="tableExtraAttrs" :init-data="initData"></customer-product-table>
            <customer-call-table v-else-if="currTabRight == 'customer-call-table'" :share-data="propsForSubComponents" :extraAttrs="tableExtraAttrs" :init-data="initData"></customer-call-table>
            <customer-task-table v-else-if="currTabRight == 'customer-task-table'" :share-data="propsForSubComponents" :extraAttrs="tableExtraAttrs" :auth="permission"></customer-task-table>
            <BaseEventTable
              v-else-if="currTabRight == 'customer-event-table'"
              module="customer"
              :share-data="propsForSubComponents"
              :otherParams="{cusId: customer.id}"/>
            <smart-plan-table v-else-if="currTabRight == 'smart-plan-table'" :customer-ids="[id]"></smart-plan-table>
            <customer-plan-table v-else-if="currTabRight == 'customer-plan-table'" :share-data="propsForSubComponents" :extraAttrs="tableExtraAttrs" :init-data="initData"></customer-plan-table>
            <customer-remind-table v-else-if="currTabRight == 'customer-remind-table'" :share-data="propsForSubComponents" :extraAttrs="tableExtraAttrs" :init-data="initData"></customer-remind-table>
            <customer-level-table v-else-if="currTabRight === 'customer-level-table'" :customerId="id"></customer-level-table>
            <task-detail-card
              ref="taskDetailCard"
              :customer-id="id"
              :is-delete="isDelete"
              :show-name-list="false"
              :form-cell-count="formCellCount"
              v-if="initData.openSuperCodePro && isAddOn(currTabRight)"
              :share-data="propsForSubComponents"
              :init-data="initData">
            </task-detail-card>
          </div>
        </template>
        <!-- end 附加组件、动态信息 -->
      </base-collapse>
    </div>
    <!-- start 客户详情折叠面板 -->

    <edit-contact-dialog ref="EditContactDialog" :customer="customer" :is-phone-unique="isPhoneUnique" />
    <edit-address-dialog ref="EditAddressDialog" :customer-id="customer.id" :default-address="initData.customerAddress" />
    <remind-customer-dialog
      ref="addRemindDialog"
      modal="customer"
      :customer="customer"
      :edited-remind="selectedRemind"
      @success-callback="selectedRemind = {}" />
    <customer-attention ref="customerAttention" @submit="updateAttentionUser" />
    <!-- 新建智能计划弹窗 -->
    <createSmartPlanDialog :customers="[customer]" ref="createSmartPlanDialog" />

    <!-- 通栏设置 -->
    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="baseLayout"
      :columns="formCellCount"
      @changeLayout="changeTaskDetailLayout">
    </biz-layout-modal>

    <merge-customer-dialog
      :currentCustomer='currentCustomer'
      pageType="detail"
      ref='mergeCustomerDialog'
      @updateCustomer="updateCustomer"
      @saveSuccess="onMergeCustomerSubmit"
    />

  </div>
</template>

<script>
import Exception from '@model/Exception'
import * as CustomerApi from '@src/api/CustomerApi.ts'
import {getCount} from '@src/api/ArchiveApi'
import Platform from '@src/platform'

import EditAddressDialog from './operationDialog/EditAddressDialog.vue'
import EditContactDialog from './operationDialog/EditContactDialog.vue'
import RemindCustomerDialog from './operationDialog/RemindCustomerDialog.vue'

import CustomerInfoRecord from './components/CustomerInfoRecord.vue'
import CustomerEventTable from './components/CustomerEventTable.vue'
import CustomerTaskTable from './components/CustomerTaskTable.vue'
import CustomerContractTable from './components/CustomerContractTable.vue';
import CustomerProductTable from './components/CustomerProductTable.vue'
import CustomerCallTable from './components/CustomerCallTable.vue'
import CustomerContactTable from './components/CustomerContactTable.vue'
import CustomerAddressTable from './components/CustomerAddressTable.vue'
import BaseEventTable from 'src/modules/event/components/BaseEventTable.vue'
import CustomerPlanTable from './components/CustomerPlanTable'
import CustomerRemindTable from './components/CustomerRemindTable'
import SmartPlanTable from '@src/modules/smartPlan/common/smartPlanTable.vue'
import CustomerAttention from './components/CustomerAttention.vue'
import CustomerDetail from './components/CustomerDetail'
import TaskCard from './components/TaskCard'
import CustomerLevelTable from './components/CustomerLevelTable.vue'
import CustomerTagEdit from '@src/modules/customer/view/components/CustomerTagEdit/CustomerTagEdit.tsx'
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'
import MergeCustomerDialog from '@src/modules/customer/list/operationDialog/MergeCustomerDialog.vue';

/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum.ts'

import {
  isBasicEditionHideProduct,
  isBasicEditionHideEvent,
  isBasicEditionHidePlanWork,
  isBasicEditionHideCallCenter
} from '@shb-lib/version'

import i18n from '@src/locales'
import AuthUtil from '@src/util/auth'
import _ from 'lodash'

import qs from '@src/util/querystring'
import http from '@src/util/HttpUtil';

import noAuth from '@src/modules/calendar/noAuth.vue'

/* util */
//
// import {
//   getEnabledCardInfo
// } from '@src/api/SettingCusProApi';

import { RESOURCE_PREFIX } from '@src/util/linkSwitch'
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { computedTabList } from '@src/util/tabBarUtils';
import { getStorageForDetailTabbar, setStorageForDetailTabbar } from '@src/api/SystemApi'
import {
  getEnabledCardInfo
} from '@src/api/SettingCusProApi';
import { migration } from '@src/component/form/util';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import { formatAddress, useStateSystemViewLayout } from 'pub-bbx-utils';

/* mixin */
import ManualTriggerMixin from '@src/mixins/manualTriggerMixin'

import { VersionControlCustomerMixin, VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

import { havePageButtonSetGray } from '@src/util/grayInfo'
import { pageButtonClick, getPageButtonListForView } from '@src/component/compomentV2/buttonSet/common'
import { ButtonGetTriggerModuleEnum, ButtonSetDetailForShowPositionEnum } from 'pub-bbx-global/pageType/dist/enum/ButtonSetEnum'
import * as FormUtil from '@src/component/form/util'

export default {
  name:'CustomerDetailViewV2',
  mixins: [ManualTriggerMixin, VersionControlCustomerMixin, VersionControlTaskMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    let tableExtraAttrs = Object.freeze({
      border: true
    })
    return {
      collapse:false,
      id: this.initData.id, // 当前客户的id
      tabs: [],
      // 当前选中的tab
      currTab: 'customer-detail',
      currTabRight:'customer-info-record',
      customerOption: {},
      remindList: [],
      selectedRemind: {},
      customer: {},
      loading: false,
      showWholeName: -1, // -1代表不显示展开icon 0代表收起 1代表展开
      StatisticalData: {},
      fieldInfo: [],
      attentionUsers: [], // 该客户的关注用户,
      collapseDirection: null,
      tableExtraAttrs,
      api: {
        getCardCache: CustomerApi.getCardCache,
        setCardCache: CustomerApi.setCardCache
      },
      archiveCount:0, // 归档工单数量
      isArchiveView:false, // 归档工单查看权限
      // labelAllList: [], // 右侧所有标签选项
      // addOnLabelList: this.initData.openSuperCode ? void 0 : [], // 右侧所有附加组件
      // addOnLabelShowList: [], // 右侧附加组件实际展示
      // labelShowList: void 0, // 右侧标签展示选择项
      // cardCacheList: void 0, // 右侧标签缓存
      // labelPrepared: false,
      // labelExtend: false,
      customerAuth: {},
      contractBtnCray: false, // 合同灰度,
      tabBarList:[],
      tabLabelKey:BaseTabBarUsualEnum.TabBarListItemLabel,
      tabNameKey:BaseTabBarUsualEnum.TabBarListItemKey,
      rightTabBarLoading:false,
      
      pageButtonSetGray:havePageButtonSetGray(),
      pageButtonList:[],
      pageButtonLoading:false,
      leftTabBarList: [],
      taskLayoutTabBarList: [],
      baseLayout: 2, // 布局方式 1:通栏 2:左右 
      tabPosition: '', // 记录tab位置  left|right
      formCellCount:1,
      currentCustomer: {}
    }
  },
  computed:{
    taskLabel(){
      const {taskQuantity, unfinishedTaskQuantity} = this.StatisticalData;
      return taskQuantity + this.archiveCount
        ? `${this.$t('common.base.task')}(${unfinishedTaskQuantity || 0}/${
          taskQuantity + this.archiveCount >= 1000 ? '999+' : taskQuantity + this.archiveCount
        })`
        : `${this.$t('common.base.task')}(0)`
    },
    eventLabel(){
      const {eventQuantity, unfinishedEventQuantity} = this.StatisticalData;
      return eventQuantity
        ? `${this.$t('common.base.event')}(${unfinishedEventQuantity || 0}/${
          eventQuantity >= 1000 ? '999+' : eventQuantity
        })`
        : `${this.$t('common.base.event')}(0)`
    },
    // 是否显示通话
    showCall(){
      return !this.isDelete && localStorage.getItem('call_center_module') == 1
    },
    isDivideByTag() {
      return this.initData.isDivideByTag
    },
    fields() {
      let fieldInfo = this.initData.fieldInfo
      let synergiesField = fieldInfo.find(v => v.fieldName === 'synergies')
      let setting = synergiesField?.setting
      if (setting) setting.max = 100

      const fields = (this.initData.fieldInfo || []).sort(
        (a, b) => a.orderId - b.orderId
      )
      return [
        ...fields,
        {
          displayName: '',
          formType: 'separator'
        },
        {
          displayName: this.$t('common.base.column.createPerson'),
          fieldName: 'createLoginUser',
          formType: 'user',
          isSystem: 1
        },
        {
          displayName: this.$t('common.base.column.createTime'),
          fieldName: 'createTime',
          formType: 'text',
          isSystem: 1
        },
        {
          displayName: this.$t('product.detail.type.id'),
          fieldName: 'id',
          formType: 'text',
          isSystem: 1
        }
      ]
    },
    /** 子组件所需的数据 */
    propsForSubComponents() {
      return {
        customer: this.customer,
        loginUser: this.initData.loginUser,
        allowEditCustomer: this.allowEditCustomer,
        isAddressAllowNull: this.initData.isAddressAllowNull,
        isPhoneUnique: this.initData.isPhoneUnique,
        isDisable: this.isDisable,
        isDelete: this.isDelete,
        loading:this.loading,
        fields:this.fields,
        cardType:'customer',
        cardAuth:this.allowEditCustomer && !this.isDelete && !this.isDisable,
        collapseDirection:this.collapseDirection,
        archiveCount:this.archiveCount,
        isArchiveView:this.isArchiveView
      }
    },
    /** 服务团队 **/
    tags(){
      const tags = this.customer.tags;
      if(Array.isArray(tags)){
        return tags.map(item=>item.tagName).join('，')
      }
      return ''

    },
    /** 联系人地址 **/
    lmAddress(){
      const address = this.customer.customerAddress || {};
      return formatAddress(address)
    },
    /** 是否关注该客户 */
    isAttention() {
      return this.attentionUsers.some(u => u.userId == this.loginUser.userId)
    },
    /**
     * 是否有查看客户权限，需要满足以下条件之一：
     *
     * 1. 查看客户全部权限： 全部客户
     * 2. 查看客户团队权限： 没有团队的客户都可查看，有团队的按团队匹配。 包含个人权限
     * 3. 查看客户个人权限： 自己创建的 或 客户负责人 或 客户协同人
     */
    hasViewCustomerAuth() {
      // 改为接口判断
      return this.customerAuth.check
    },
    eventTypes() {
      if (!this.initData || (this.initData && !this.initData.eventTypeList))
        return []
      return this.initData.eventTypeList.map(t => Object.freeze(t))
    },
    // 工单类型列表
    taskTypes() {
      if(!this.initData?.taskTypeList?.length) return []
      return this.initData.taskTypeList.map((t) => Object.freeze(t));
    },
    // 计划任务类型列表
    planTypeList() {
      if(!this.initData?.planTypeList?.length) return []
      return this.initData.planTypeList.map((t) => Object.freeze(t));
    },
    /** 是否显示返回按钮 */
    allowBack() {
      let allow = true

      // 如果带入noHistory参数，则不显示
      let query = qs.parse(window.location.search)
      if (query.noHistory) return false

      // 验证路径
      let path = window.location.pathname
      if(path.indexOf(RESOURCE_PREFIX) > -1) path = path.replace(RESOURCE_PREFIX, '')
      let disablePathReg = [/^\/customer\/view\/\S+$/]
      if (disablePathReg.some(reg => reg.test(path))) return false

      return allow
    },
    /**
     * 满足以下条件允许为客户添加产品
     * 1. 客户没有被删除
     * 2. 产品创建权限
     */
    allowCreateProduct() {
      return !this.isDelete && this.permission.PRODUCT_CREATE
    },
    /**
     * 满足以下条件允许编辑客户
     * 1. 客户没有被删除
     * 2. 有客户编辑权限
     */
    allowEditCustomer() {
      return !this.isDelete && this.hasEditCustomerAuth
    },
    allowCreateCustomer() {
      return this.permission.CUSTOMER_CREATE
    },
    /**
     * 客户是否被删除
     * 在客户删除时不允许做任何操作，只能查询
     * 所有操作的权限应该以此为基础
     */
    isDelete() {
      return this.customer.isDelete === null || this.customer.isDelete === 1
    },
    isShowTaskModule() {
      return this._isShowTaskModule
    },
    /* 是否显示客户提醒 */
    isShowCustomerRemind() {
      return this._isShowCustomerRemind
    },
    isShowCustomerTag() {
      return this._isShowCustomerTag
    },
    allowDeleteCustomer() {
      return !this.isDelete && this.permission.CUSTOMER_DELETE
    },
    /** 客户是否被禁用 */
    isDisable() {
      return this.customer.status === null || this.customer.status === 0
    },
    isPhoneUnique() {
      return this.initData.isPhoneUnique
    },
    /** 当前登录的用户 */
    loginUser() {
      return this.initData.loginUser || {}
    },
    /**
     * 满足以下提交见允许创建工单
     *
     * 1. 客户没被删除
     * 2. 客户没被禁用
     * 3. 客户编辑权限
     * 4. 创建工单权限
     */
    allowCreateTask() {
      return (
        !this.isDelete
        && !this.isDisable
        // this.hasEditCustomerAuth &&
        && AuthUtil.hasAuth(this.permission, 'TASK_ADD')
      )
    },
    /**
     * 满足以下提交可以创建事件
     *
     * 1. 客户没有被删除
     * 2. 客户没有被禁用
     * 3. 客户编辑权限
     * 4. 新建事件权限
     */
    allowCreateEvent() {
      return (
        !this.isDelete
        && !this.isDisable
        // this.hasEditCustomerAuth &&
        && AuthUtil.hasAuth(this.permission, 'CASE_ADD')
      )
    },
    /**
     * 满足以下条件可以创建计划任务
     *
     * 1. 客户没有被删除
     * 2. 客户没有被禁用
     * 3. 启用计划任务
     * 4. 客户编辑权限
     * 5. 工单新建权限和工单指派权限
     */
    allowCreatePlanTask() {
      let planTaskEnabled = this.initData.planTaskEnabled
      return (
        !this.isDelete
        && !this.isDisable
        && this.hasEditCustomerAuth
        && planTaskEnabled
        && AuthUtil.hasEveryAuth(this.permission, ['TASK_ADD', 'TASK_DISPATCH'])
      )
    },
    /* 是否显示计划任务 */
    isShowPlanTask() {
      return this._isShowTaskPlanTask && !this.smartPlanGray
    },
    // 是否显示更多操作
    isShowMoreOperation() {
      return this.isShowCreateSmartPlan || (this.pageButtonSetGray && this.pageButtonList.length)
    },
    /** 当前用户的权限 */
    permission() {
      return (this.initData.loginUser || {}).authorities
    },
    /**
     * 是否有编辑客户权限，需要满足以下条件之一：
     *
     * 1. 编辑客户全部权限： 全部客户
     * 2. 编辑客户团队权限： 没有团队的客户都可编辑，有团队的按团队匹配。 包含个人权限
     * 3. 编辑客户个人权限： 自己创建的 或 客户负责人 或 客户协同人
     */
    hasEditCustomerAuth() {
      let customer = this.customer
      let loginUserId = this.loginUser.userId
      return AuthUtil.hasAuthWithDataLevel(
        this.permission,
        'CUSTOMER_EDIT',
        // 团队权限判断
        () => {
          let tags = Array.isArray(customer.tags) ? customer.tags : []
          // 无团队则任何人都可编辑
          if (tags.length == 0) return true

          let loginUserTagIds = this.initData.loginUser.tagIdsWithChildTag || []
          return tags.some(tag => loginUserTagIds.indexOf(tag.id) >= 0)
        },
        // 个人权限判断
        () => {
          return customer.createUser == loginUserId || this.isCustomerManagerOrSynergies
        }
      )
    },
    /**
     * 当前用户是否是该客户负责人
     * 客户负责人用于和客户创建人相同权限
     */
    isCustomerManager() {
      return this.loginUser.userId === this.customer.customerManager
    },
    /**
     * 当前用户是否是该客户协同人
     */
    isCustomerSynergies() {
      let customerSynergies = this.customer.synergies || []
      return !!customerSynergies.find(v => v.userId === this.loginUser.userId)
    },

    /**
     * 当前用户是否是该客户负责人或协同人
     */
    isCustomerManagerOrSynergies() {
      return this.isCustomerManager || this.isCustomerSynergies
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct()
    },
    // 基础版功能是否隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent()
    },
    // 基础版功能是否隐藏计划任务
    isBasicEditionHidePlanWork() {
      return isBasicEditionHidePlanWork()
    },
    // 基础版功能是否隐藏通话
    isBasicEditionHideCallCenter() {
      return isBasicEditionHideCallCenter()
    },
    // 是否有编辑联系人权限
    allowCreateLinkman() {
      return this.permission?.LINKMAN_ADD
    },
    // 是否有编辑联系人权限
    allowEditLinkman() {
      return this.permission?.LINKMAN_EDIT
    },
    // 是否有删除联系人权限
    allowDeleteLinkman() {
      return this.permission?.LINKMAN_DELETE
    },
    hidePartCollapse() {
      if (this.baseLayout === 1) return this.tabPosition === 'left' ? 'right' : 'left';
      return '';
    },
    // 是否显示客户层级tab
    isShowCustomerLevel() {
      return this.initData?.fieldInfo.some(v => v.fieldName === 'parentCustomer');
    },
  },
  methods:{
    getPageButtonListForView,
    // 自定义按钮点击事件
    handlePageButtonClick(item) {
      pageButtonClick(item, [this.customer], {
        fields: this.fields,
        multipleSelection: this.multipleSelection,
        js_vm: this,
      })
    },
    /**合并客户成功 */
    onMergeCustomerSubmit(){
      let fromId = window?.frameElement?.getAttribute('fromid')
      this.$platform.refreshTab(fromId)
      window.location.reload()
    },
    // 获取合同灰度
    getContractGray() {
      CustomerApi.getContractGray({
        code: 'CONTRACT'
      }).then(res => {
        if (res.succ) {
          this.contractBtnCray = res.data.CONTRACT;
        }
      })
    },
    async customerCheckAuth() {
      let query = qs.parse(window.location.search)
      let params = {
        customerId: this.id,
        sourceCustomerId: query?.sourceCustomerId || void 0,
        fieldName: query?.fieldName || void 0
      }
      try {
        let res = await CustomerApi.customerCheckAuth(params)
        if (res.code !== 0) return

        this.customerAuth = res.result || {}
      } catch (error) {
        console.log(error)
      }
    },
    // 获取归档工单数量
    async getCount(){
      const params = {
        customerId:this.id
      }
      const {code, message, result} = await getCount(params);
      if(code === 0){
        this.archiveCount = result.archiveCount;
        this.isArchiveView = result.isArchiveView;
      }else{
        this.$notify({
          title: this.$t('common.base.fail'),
          message,
          type: 'error'
        });
      }
    },
    selectTab(tab) {
      this.currTab = tab
    },
    updateRemind(remind) {
      this.selectedRemind = remind || {}
      this.$nextTick(() => {
        this.$refs.addRemindDialog.openDialog(
          this.selectedRemind.sendRoleSetting || {}
        )
      })
    },
    /** 从客户创建工单 */
    createTask(typeId) {
      let customer = this.customer || {}
      let fromId = window.frameElement.getAttribute('id')

      // this.$platform.openTab({
      //   id: 'createTask',
      //   title: '新建工单',
      //   close: true,
      //   url: `/task/createFromCustomer/${customer.id}?defaultTypeId=${typeId}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateTaskFromCustomer,
        key: customer.id,
        params: `defaultTypeId=${typeId}`,
        fromId
      })
    },
    /** 从客户创建事件 */
    createEvent(typeId) {
      let customer = this.customer || {}
      let fromId = window.frameElement.getAttribute('id')

      // this.$platform.openTab({
      //   id: 'createEvent',
      //   title: '新建事件',
      //   close: true,
      //   url: `/event/createFromCustomer/${customer.id}?defaultTypeId=${typeId}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateEventFromCustomer,
        key: customer.id,
        params: `defaultTypeId=${typeId}`,
        fromId
      })
    },
    /** 从客户创建计划工单 */
    createPlanTask(typeId) {
      let customer = this.customer || {}
      let fromId = window.frameElement.getAttribute('id')

      // this.$platform.openTab({
      //   id: 'createPlan',
      //   title: '新建计划任务',
      //   close: true,
      //   url: `/task/planTask/create?defaultTypeId=${typeId}&customerId=${customer.id}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePlanTaskCreate,
        params: `defaultTypeId=${typeId}&customerId=${customer.id}`,
        fromId
      })
    },
    // 滚动
    getScroll() {
      this.collapse = false
    },
    openMap() {
      this.$fast.map
        .display(this.customer.customerAddress, {title: this.$t('common.base.address')})
        .catch(err => console.error('openMap catch an err: ', err));
    },
    async makephoneCall(){
      if(!this.customer.lmPhone) return
      try {
        const { code, message } = await http.post('/api/callcenter/outside/callcenter/api/dialout', {phone:this.customer.lmPhone, taskType:'customer'}, false)
        if (code !== 0) return this.$platform.notification({
          title: this.$t('customer.detail.callNotify.title'),
          message: message || '',
          type: 'error',
        })
      } catch (error) {
        console.error(error);
      }
    },
    /** 取消某些用户对该客户的关注 */
    async updateAttentionUser({ removeUsers, userName }) {
      try {
        let params = {
          customerId: this.id,
          userIds: removeUsers.map(u => u.userId).join(',')
        }

        let result = await CustomerApi.cancelAttention(params)
        // 这里推荐至直接throw Exception
        if (result.status == 1) throw new Exception(result.message)

        Platform.notification({
          type: 'success',
          title: this.$t('customer.detail.attentionUserNotify.cancelTitle'),
          message: this.$t('customer.detail.attentionUserNotify.cancelMessage', {userName})
        })

        this.fetchAttentionUsers()
        this.$eventBus.$emit('customer_info_record.update_record_list')
      } catch (e) {
        if (e instanceof Exception) {
          Platform.notification({
            type: 'error',
            title: this.$t('common.base.fail'),
            message: e.message
          })
        }
      }
    },
    /** 抓取该客户的关注列表 */
    async fetchAttentionUsers() {
      try {
        let params = { customerId: this.id }
        let result = await CustomerApi.attentionList(params)

        if (result.status == 0) {
          this.attentionUsers = result.data || []
        }
      } catch (error) {
        console.error(error)
      }
    },
    execAttentionCommand(command) {
      if (command == 'toggle') return this.toggleAttention()
      if (command == 'view') {
        return (
          this.hasEditCustomerAuth
          && this.$refs.customerAttention.view(this.attentionUsers)
        )
      }
    },
    /** 切换该客户的关注状态 */
    async toggleAttention(event) {
      this.$track.clickStat(this.getBtnsTrackData(`${this.isAttention ? 'UN_FOLLOW_CUSTOMER' : 'FOLLOW_CUSTOMER'}`))
      try {
        let params = {
          customerId: this.id,
          module: 'customer',
          action: this.isAttention ? '取消关注' : '关注'
        }

        let result = await CustomerApi.toggleAttention(params)
        // 这里推荐至直接throw Exception
        if (result.status == 1) throw new Exception(result.message)

        Platform.notification({
          type: 'success',
          title: this.isAttention ? this.$t('customer.detail.attentionNotify.cancelTitle') : this.$t('customer.detail.attentionNotify.title'),
          message: this.isAttention
            ? this.$t('customer.detail.attentionNotify.cancelMessage')
            : this.$t('customer.detail.attentionNotify.message')
        })

        this.fetchAttentionUsers()
        this.fetchStatisticalData()
        this.$eventBus.$emit('customer_info_record.update_record_list')
      } catch (e) {
        if (e instanceof Exception) {
          Platform.notification({
            type: 'error',
            title: this.$t('common.base.fail'),
            message: e.message
          })
        }
      }
    },
    async fetchStatisticalData() {
      const params = {
        forceAllData: true,
        customerId: this.initData.id || this.customer.id
      }
      let callCount = 0
      try {
        const res = await this.$http.get('/api/callcenter/outside/callcenter/callrecord/total4CallTab', params)
        callCount = res.result || 0
      } catch (error) {
        console.error(error);
      }
      this.$http
        .get('/customer/statistics/init', params)
        .then(res => {
          if (Object.keys(res).every(key => key !== 'taskQuantity')) return

          this.StatisticalData = res
          this.StatisticalData.callQuantity = callCount
          localStorage.setItem('customer_remind_count', res.remindQuantity)
          this.$nextTick(()=>{
            this.loading = false;
            !this.ifResizeWatch && this.initRightTabBar()
          })
        })
        .catch(err => console.error('fetchStatisticalData', err))
    },
    async deleteCustomer() {
      try {
        if (!(await this.$platform.confirm(this.$t('customer.detail.delCustomerConfirm.message')))) return

        const params = { ids: this.customer.id }
        const result = await this.$http.post('/customer/delete', params)
        if (!result.status) {
          let id = window.frameElement.dataset.id
          this.$platform.closeTab(id)

          // let fromId = window.frameElement.getAttribute('fromid')
          // this.$platform.refreshTab(fromId)

          // window.location.reload()
        }
      } catch (e) {
        console.error('customer-detail-view deleteCustomer error', e)
      }
    },
    jump() {
      let currTabId = window.frameElement.dataset.id;
      // 跳转之前 修改tab标题
      this.$platform.setTabTitle({
        id: currTabId,
        title: this.$t('common.pageTitle.pageCustomerRegisterEdit'),
      })
      const id = this.id || this.initData.id
      window.location.href = `${this.$resourcePrefix}/customer/edit/${id}`
    },
    // 折叠按钮
    collapseBtn(){
      this.$refs.container.scrollTop = 0;
      this.collapse = !this.collapse;
    },
    handleCommand(type){
      if(type === 'contact' || type === 'address'){
        this.openDialog(type);
      }else{
        this.createProduct('address')
      }
    },
    openDialog(action) {
      if (action === 'address') {
        this.$refs.EditAddressDialog.openDialog()
      } else if (action === 'contact') {
        this.$refs.EditContactDialog.openDialog(this.customer);
      } else if (action === 'remark') {
        this.$refs.addRemarkDialog.openDialog()
      } else if (action === 'remind') {
        this.$refs.addRemindDialog.openDialog()
      }
    },
    createProduct() {
      const id = this.id || this.initData.id
      let fromId = window.frameElement.getAttribute('id')
      // this.$platform.openTab({
      //   id: 'customer_product_create',
      //   title: '新建产品',
      //   url: `/customer/product/create?customerId=${id}`,
      //   reload: true,
      //   close: true,
      //   fromId: window.frameElement.getAttribute('id'),
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateProduct,
        params: `customerId=${id}`,
        reload: true,
        fromId
      })
      // window.location.href = `/customer/product/create?customerId=${id}`
    },
    fetchCustomer() {
      const id = this.initData.id
      this.$http
        .get('/customer/get', { id })
        .then(async res => {
          if (res.status) return
          this.customer = _.cloneDeep(res.data)
          // 处理富文本
          this.customer = await FormUtil.initRichTextContent(this.fields, this.customer)
          this.currentCustomer = this.customer;

        })
        .catch(err =>
          console.error(
            'customer-detail-view fetchCustomer catch error /n',
            err
          )
        )
    },
    onCustoemrTagChangeHandler(value) {
      this.customer.customerTag = value.slice()
      this.$eventBus.$emit('customer_detail_view.update_statistical_data')
      this.$eventBus.$emit('customer_info_record.update_record_list')
    },

    // 协同人更新
    synergiesUpdated(synergies) {
      this.customer.synergies = synergies
      this.$eventBus.$emit('customer_info_record.update_record_list')
    },
    /**
     * @des 初始化tabBar
     */
    async initRightTabBar() {
      // 通栏模式tabPosition默认left
      if (this.baseLayout === 1) {
        this.tabPosition = 'left'
      }
      let { TabBarListItemKey:tabName, TabBarListItemLabel:tabLabel, TabBarListItemShow:tabShow, TabBarCardInfoType:tabIsCardType, TabCardInfoSingle:tabIsCardSingle, TabBarListItemType:tabType } = BaseTabBarUsualEnum;
      let cardInfoList = [];
      this.rightTabBarLoading = true;
      try {
        // 获取附加组件列表
        let { result, code, message } = await getEnabledCardInfo({cardType:this.propsForSubComponents.cardType});
        if(code !== 0){
          throw message
        }
        cardInfoList = result.map(item=>{
          const { id, name, nameLanguage, fields} = item;
          return {
            ...item,
            fields: migration(fields || []),
            [tabName]: `${tabIsCardSingle}${id}`,
            [tabLabel]: nameLanguage?.[i18n.locale] || name,
            [tabShow]:true,
            [tabType]:tabIsCardType
          }
        })
      } catch (error) {
        console.warn(error, 'error try catch getEnabledCardInfo');
      }

      this.leftTabBarList = [
        { position: 'left', tabLabel: this.$t('common.base.customerInfo'), tabName: 'customer-detail', tabShow: true},
      ]

      let barArr = [
        {[tabName]:"customer-info-record", disabled:true, [tabLabel]: this.$t('customer.detail.tabBar.dynamicInfo'), [tabShow]:true},
        ...(!this.isDelete ? [{[tabName]:"customer-contact-table", [tabLabel]:this.$t('customer.detail.tabBar.contact'), [tabShow]:true }] : []),
        ...(!this.isDelete ? [{[tabName]:"customer-address-table", [tabLabel]:this.$t('customer.detail.tabBar.address'), [tabShow]:true }] : []),
        ...(!this.isDelete && this.contractBtnCray && this._isShowCustomerContract ? [{[tabName]:"customer-contract", [tabLabel]:this.$t('customer.detail.tabBar.contract'), [tabShow]:true }] : []),
        ...(!this.isDelete && !this.isBasicEditionHideProduct ? [{[tabName]:"customer-product-table", [tabLabel]:this.$t('customer.detail.tabBar.product'), [tabShow]:true }] : []),
        ...(this.showCall && !this.isBasicEditionHideCallCenter ? [{[tabName]:"customer-call-table", [tabLabel]:this.$t('customer.detail.tabBar.call'), [tabShow]:true }] : []),
        ...(this.isShowTaskModule ? [{[tabName]:"customer-task-table", [tabLabel]:this.$t('customer.detail.tabBar.task'), [tabShow]:true }] : []),
        ...(!this.isBasicEditionHideEvent ? [{[tabName]:"customer-event-table", [tabLabel]:this.$t('customer.detail.tabBar.event'), [tabShow]:true }] : []),
        ...(this.smartPlanGray ? [{[tabName]: 'smart-plan-table', [tabLabel]: this.$t('smartPlan.title'), [tabShow]:true }] : []),
        ...(this.allowCreatePlanTask && this.isShowPlanTask && !this.isBasicEditionHidePlanWork ? [{[tabName]:"customer-plan-table", [tabLabel]:this.$t('customer.detail.tabBar.scheduledTasks'), [tabShow]:true }] : []),
        ...(!this.isDelete && !this.isDisable && this.isShowCustomerRemind ? [{[tabName]:"customer-remind-table", [tabLabel]:this.$t('customer.detail.tabBar.remind'), [tabShow]:true }] : []),
        ...(this.parentCustomerGray && this.isShowCustomerLevel ? [{[tabName]: "customer-level-table", [tabLabel]: this.$t('common.form.preview.customer.customerLevel'), [tabShow]: true}] : []),
        ...cardInfoList
      ]
      barArr.forEach(tab => {
        tab.needTrack = true
        tab.position = 'right'
      })
      let parasm_ = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Customer,
        bizTypeId:'0'
      }
      try {
        // 获取tabbar用户行为缓存
        let storageList = await getStorageForDetailTabbar(parasm_);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        console.log(storageList_, 'storageList_')
        barArr = computedTabList(barArr, storageList_)
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }
      this.tabBarList = barArr;
      this.$nextTick(()=>{
        let firstItem = barArr && barArr.find(item=>item[tabShow])
        this.currTabRight = firstItem?.[tabName];
        this.rightTabBarLoading = false;
      })
    },
    tabBarChangeItem(item){
      let { TabBarListItemKey:tabName, TabBarListItemType:tabType, TabBarCardInfoType } = BaseTabBarUsualEnum;
      this.$refs.rightContent.scrollTo(0, 0)

      let { position } = item
      this.tabPosition = position

      // 通栏导航和左侧导航共用leftActiveTab数据
      if (this.baseLayout === 1 || position == 'left') {
        this.currTab = item[tabName];
      }
      // 右侧导航
      if (position == 'right') {
        this.currTabRight = item[tabName];
      }

      if (item[tabType] == TabBarCardInfoType) {
        this.$nextTick(() => {
          let taskDetailCard = this.$refs.taskDetailCard;
          taskDetailCard && (taskDetailCard.activeTab = item.id)
        })
      }
    },
    /**
     * @des tabbar数据发生变更钩子函数
     */
    tabBarUpdateList(list){
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let parasm_ = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Customer,
        bizTypeId:'0',
        cardList:list_
      }
      setStorageForDetailTabbar(parasm_)
    },
    // 是否是附加组件
    isAddOn (key) {
      let str = BaseTabBarUsualEnum.TabCardInfoSingle;
      return key.startsWith(str)
    },

    getBtnsTrackData(id, data) {
      return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
    },
    handleMoreOperationCommand(command) {
      if(!command) return
      if (command == 'smartPlan') {
        this.$refs.createSmartPlanDialog.open()
      } else if (command?.type == 'trigger') {
        this.handleManualTrigger(command.id, [this.customer.id])
      } else if (command == 'mergeCustomer') {
        this.$refs.mergeCustomerDialog.selectedCustomers =  [this.customer]
        this.$refs.mergeCustomerDialog.open()
      }
    },
    updateCustomer(value){
      this.selectedCustomers = value;
    },
    // 打开通栏
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeTaskDetailLayout(type, columns) {
      this.baseLayout = type;
      this.currTab = this.leftTabBarList[0]?.tabName;
      this.tabPosition = 'left';
      if (type === 2) {
        this.currTabRight = this.tabBarList[0].tabName
      }
      this.formCellCount = columns * 1;

    },
    async initLayoutData(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      this.baseLayout = count.baseLayout || 2;
      this.formCellCount = count.formCellCount || 1;
    }
  },
  components:{
    [CustomerInfoRecord.name]: CustomerInfoRecord,
    [CustomerEventTable.name]: CustomerEventTable,
    [CustomerTaskTable.name]: CustomerTaskTable,
    [CustomerProductTable.name]: CustomerProductTable,
    [CustomerCallTable.name]: CustomerCallTable,
    [CustomerContactTable.name]: CustomerContactTable,
    [CustomerAddressTable.name]: CustomerAddressTable,
    [CustomerPlanTable.name]: CustomerPlanTable,
    [CustomerRemindTable.name]: CustomerRemindTable,
    [SmartPlanTable.name]: SmartPlanTable,
    [EditAddressDialog.name]: EditAddressDialog,
    [EditContactDialog.name]: EditContactDialog,
    [RemindCustomerDialog.name]: RemindCustomerDialog,
    [CustomerAttention.name]: CustomerAttention,
    [CustomerDetail.name]:CustomerDetail,
    [TaskCard.name]:TaskCard,
    [ComponentNameEnum.CustomerTagEdit]: CustomerTagEdit,
    [noAuth.name]: noAuth,
    [CustomerContractTable.name]: CustomerContractTable,
    [CustomerLevelTable.name]: CustomerLevelTable,
    BaseBarV3,
    BaseTileLayoutTabBar,
    BaseEventTable,
    [MergeCustomerDialog.name]: MergeCustomerDialog
  },
  watch: {
    collapse(newValue) {
      sessionStorage.setItem(`customer_collapse_${this.customer.id}`, newValue);
    },
    collapseDirection(newValue) {
      sessionStorage.setItem(`customer_collapseDirection_${this.customer.id}`, newValue);
    },
    hasViewCustomerAuth: {
      handler(newValue) {
        if (!newValue) {
          document.body.classList.add('body-no-auth')
        } else {
          document.body.classList.remove('body-no-auth')
        }
      },
      immediate: true
    },
    leftTabBarList: {
      handler() {
        this.taskLayoutTabBarList = _.cloneDeep([...this.leftTabBarList, ...this.tabBarList].filter(item => item.tabShow));
      }
    },
    tabBarList: {
      handler() {
        this.taskLayoutTabBarList = _.cloneDeep([...this.leftTabBarList, ...this.tabBarList].filter(item => item.tabShow));
      }
    }
  },
  created(){
    // 折叠面板缓存
    // let collapse = sessionStorage.getItem(`customer_collapse_${this.initData.id}`);
    let collapseDirection = sessionStorage.getItem(`customer_collapseDirection_${this.initData.id}`);

    // this.collapse = JSON.parse(collapse || 'true');
    this.collapseDirection = collapseDirection || '';
    if(this.pageButtonSetGray){
      this.getPageButtonListForView(ButtonGetTriggerModuleEnum.Customer, ButtonSetDetailForShowPositionEnum.PcDetail,  {}, (list)=>{
        this.pageButtonList = list
      })
    }
    this.initLayoutData()
  },
  async mounted(){
    this.loading = true
    await this.getContractGray()
    await this.customerCheckAuth()
    if (!this.hasViewCustomerAuth) {
      this.loading = false
      return
    }

    this.fetchCustomer();
    this.fetchStatisticalData();
    this.fetchAttentionUsers();
    this.getCount();
    this.getTriggerList(['customer', 'CUSTOMER_ADDITIONAL'])

    let query = qs.parse(window.location.search)
    if (query && query.active === 'contact') {
      this.currTabRight = 'customer-contact-table';
    }

    this.$eventBus.$on('customer_detail_view.update_remind', this.updateRemind)
    this.$eventBus.$on(
      'customer_detail_view.update_statistical_data',
      this.fetchStatisticalData
    )
    this.$eventBus.$on(
      'customer_detail_view.update_customer_detail',
      this.fetchCustomer
    )
    this.$eventBus.$on('customer_detail_view.select_tab', this.selectTab)

    // this.getCardCache()
    // this.getEnabledCardInfo()

  },
  beforeDestroy(){
    this.$eventBus.$off('customer_detail_view.update_remind', this.updateRemind)
    this.$eventBus.$off(
      'customer_detail_view.update_statistical_data',
      this.fetchStatisticalData
    )
    this.$eventBus.$off(
      'customer_detail_view.update_customer_detail',
      this.fetchCustomer
    )
    this.$eventBus.$off('customer_detail_view.select_tab', this.selectTab)
  }
}
</script>

<style lang="scss">
@import '@src/modules/task/view/TaskDetailView.scss';
</style>

<style lang="scss">
.task-detail-container {
    .v-step[data-v-7c9c03f0] {
        background: #fff !important;
        color: #333 !important;
        -webkit-filter: drop-shadow(0px 9px 28px 8px rgba(0, 0, 0, 0.05)) !important;
        filter: drop-shadow(0px 9px 28px 8px rgba(0, 0, 0, 0.05)) !important;
        padding: 0 !important;
        min-width: 240px !important;
        max-width: 350px !important;
    }

    .v-step .v-step__arrow[data-v-7c9c03f0] {
        border-color: #fff !important;
        border-left-color: transparent !important;
        border-right-color: transparent !important;
    }
    .v-tour-content-box {
    position: relative;
    overflow: hidden;
    padding: 0 20px;
    border-radius: 4px;
    .v-tour-left-tips {
      width: 80px;
      height: 32px;
      background: $color-primary;
      color: #fff;
      position: absolute;
      left: -40px;
      top: 0px;
      line-height: 40px;
      font-size: 12px;
      transform-origin: center top;
      transform: rotateZ(-45deg);
      text-align: center;
    }
    .v-tour-content {
      .v-tour-content-head {
        padding-top: 32px;
        padding-bottom: 10px;
        .iconfont {
          font-size: 10px;
          margin-bottom: 2px;
          color: #999;
          cursor: pointer;
        }
      }
      .v-tour-content-con {
        text-align: start;
        padding-bottom: 12px;
      }
    }
  }

  .v-tour-bottom {
    height: 52px;
    padding: 0 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .btns {
      width: 60px;
      height: 28px;
      background: $color-primary;
      color: #fff;
      text-align: center;
      line-height: 28px;
      border-radius: 4px;
    }
    .text {
      color: $color-primary;
    }
    :nth-child(n) {
      cursor: pointer;
    }
    :not(:last-child) {
      margin-right: 12px;
    }
  }

  /* 向上的箭头 */

  .normal-arrow-top {
    font-size: 0;
    line-height: 0;
    border-width: 0.5rem;
    border-color: #fff;
    width: 0;
    border-top-width: 0;
    border-style: dashed;
    border-bottom-style: solid;
    border-left-color: transparent;
    border-right-color: transparent;
    position: absolute;
    top: -0.5rem;
  }
    .guide-model-box {
        position: fixed;
        width: 100%;
        height: 100vh;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.5);
        z-index: 996;
    }

    .guide-point {
        z-index: 997;
        position: sticky;
    }

    .bg-w {
        background: #fff;
    }

    .task-detail-step-2-box {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 997;

        .task-detail-step-2 {
            width: 104px;
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            top: 0;
            left: 0;
            position: absolute;
            background: transparent;
        }
    }
}
</style>

<style lang="scss" scoped>
// ::v-deep .el-table--border{
// border:1px solid #ebeef5 !important;
// }
.task-detail-header {
  padding: 0 16px;
}
.task-detail-header-top{
  padding: 12px 0 4px 0;
  .task-detail-btn-group{
    display: flex;
    align-items: center;
  }
  button{
    margin-bottom: 8px;
  }
}
.header-right-buttons ::v-deep .el-dropdown{
  margin-left: 12px;
}
.customer-name{
  font-size: 18px;
  position: relative;
  top: -3px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}
.task-detail-container{
  // .el-button{
  //   max-width: 94px;
  // }
  .btn-icon {
    cursor: pointer;
    margin:0 5px;
  }
}
.task-detail-main-content .el-tabs__content .el-tab-pane{
  overflow: auto;
}
.task-detail-header-bottom{
  height: auto;
  ul{
    display: flex;
    justify-content: space-between;
    padding: 10px 160px 0 10px;

    li{
      width: 33%;
      div{
        height: 26px;
        display: flex;
        align-items: baseline;

        i{
          cursor: pointer;
          color:$color-primary;
        }
        .tag-name{
          color:$text-color-secondary;
          white-space: nowrap;

          + span{
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            word-break: break-all;
          }
        }
      }
      .address-item{
        display: flex;

        .address-text{
          white-space: inherit;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          cursor: pointer;
          -webkit-box-orient: vertical;
        }
        .address-text:hover{
          color:$color-primary-light-6
        }
      }
    }
  }
}
.task-detail-header-bottom.active{
  height: 0;
}

.task-detail-main {
  flex: 1;
  overflow: auto;

  .task-detail-main-content-right{
    background: #fff;
  }
}

.customer-detail-view-v2 {
  .customer-tag-edit {
    margin-left: 16px;
  }
}
.bbx-base-tab-bar-box{
  background-color: $bg-color-l2;
}

.task-type-dropdown-group {
  display: flex;
  flex-flow: column;
  max-height: 70vh;
  overflow: auto;
}
</style>
<style lang="scss">
  @import "@src/assets/scss/common-detail.scss";
.detail-main-content {
  height: 100%;
  &-right {
    height: 100%;
    overflow-x: hidden !important;
    overflow-y: auto !important;
  }
}
.detail-more-dropdown-menu .el-dropdown-menu__item {
  width: initial;
  max-width: 180px;
  @include text-ellipsis();
}
</style>
<style lang="scss" scoped>
.customer-content-left {
  display: flex;
  flex-direction: column;
  &-cell {
    flex: 1;
    overflow: hidden;
    &-con {
      overflow-y: auto;
      height: 100%;
    }
  }
}
</style>
